package com.sy.controller;

import com.sy.dto.ExpRecord;
import com.sy.dto.JsonResult;
import com.sy.dto.LoginRecord;
import com.sy.entity.LocateInfos;
import com.sy.entity.User;
import com.sy.exception.BilibiliException;
import com.sy.mapper.PersonalMapper;
import com.sy.redis.RedisClient;
import com.sy.service.PersonalService;
import com.sy.service.UserService;
import com.sy.utils.BilibiliUtils;
import com.sy.utils.RandomUtils;
import com.sy.utils.SmsUtils;
import com.sy.utils.StateUtils;
import com.sy.vo.UserVo;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static com.sy.constant.BusinessConstant.*;
import static com.sy.constant.ExpConstant.LOGIN_EXP_AWARD;

/**
 * @author zbbstart
 * @date 2021/1/12 - 18:58
 */
@RestController
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private RedisClient redisClient;
    @Autowired
    private PersonalService personalService;

    private String key = REDIS_LOGIN_PREFIX + COOKIE_LOGIN_NAME;

    /**
     * 注册
     *
     * @param userVo 前端传来的注册参数
     * @param res    状态码响应
     * @return JSON格式
     */
    @RequestMapping(value = "users/{userPhone}", method = RequestMethod.POST)
    public JsonResult regist(@PathVariable String userPhone, @RequestBody UserVo userVo, HttpServletResponse res) {
        JsonResult result = new JsonResult();
        userVo.setUserPhone(userPhone);
        System.out.println(userVo);
        try {
            boolean regist = userService.regist(userVo);
            if (regist) {
                result.setCode(200);
                result.setErrMsg(userVo.getUserName());
            } else {
                result.setCode(400);
                result.setErrMsg("添加失败");
                res.setStatus(result.getCode());
            }
        } catch (Exception e) {
            e.printStackTrace();
            result = StateUtils.is500(res);
        }
        return result;
    }

    /**
     * 发送短信验证码
     *
     * @param userPhone 用户的手机号
     * @param req       请求
     * @param res       响应
     * @return JSON格式
     */
    @RequestMapping(value = "users/{userPhone}", method = RequestMethod.GET)
    public JsonResult sendCode(@PathVariable String userPhone, HttpServletRequest req, HttpServletResponse res) {
        JsonResult result = new JsonResult();
        String code = RandomUtils.getRandomString(4);
        System.out.println(code);
        //将验证码存入Session
        req.getSession().setAttribute(SESSION_CODE_NAME, code);
        //封装的短信接口
        try {
            SmsUtils.sendMsg(userPhone, code);
            result.setCode(200);
        } catch (BilibiliException e) {
            e.printStackTrace();
            result.setCode(400);
            res.setStatus(result.getCode());
            result.setErrMsg(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            result = StateUtils.is500(res);
        }
        return result;
    }

    /**
     * 查询用户是否存在
     *
     * @param req 请求
     * @param res 响应
     * @return JSON格式
     */
    @RequestMapping(value = "users", method = RequestMethod.GET)
    public JsonResult getUserByUserName(HttpServletRequest req, HttpServletResponse res) {
        JsonResult result = new JsonResult();
        String userName = req.getParameter("userName");
        try {
            User user = userService.getUserByUserName(userName);
            if (null != user) {
                result.setCode(200);
                result.setData(user.getUsername());
            } else {
                result.setCode(404);
                res.setStatus(result.getCode());
                result.setErrMsg("用户不存在，请您先注册");
            }
        } catch (Exception e) {
            e.printStackTrace();
            result = StateUtils.is500(res);
        }
        return result;
    }

    /**
     * 查询手机号是否被注册
     *
     * @param userPhone 用户手机号
     * @param res       响应
     * @return JSON格式
     */
    @RequestMapping(value = "phones/{userPhone}", method = RequestMethod.GET)
    public JsonResult getUserByPhone(@PathVariable(required = false) String userPhone, HttpServletResponse res) {
        JsonResult result = new JsonResult();
        System.out.println(userPhone);
        User phone = userService.getUserByPhone(userPhone);
        try {
            if (null != phone) {
                result.setCode(200);
                result.setData(phone.getUserphone());
            } else {
                result.setCode(404);
                res.setStatus(result.getCode());
                result.setErrMsg("手机号未注册");
            }
        } catch (Exception e) {
            e.printStackTrace();
            result = StateUtils.is500(res);
        }
        return result;
    }

    /**
     * 密码登录
     *
     * @param req 请求
     * @param res 响应
     * @return JSON格式
     */
    @RequestMapping(value = "users/pwd", method = RequestMethod.GET)
    public JsonResult loginByPwd(HttpServletRequest req, HttpServletResponse res) {
        JsonResult result = new JsonResult();
        String userName = req.getParameter("userName");
        String passWord = req.getParameter("passWord");
        String flag = req.getParameter("flag");
        System.out.println(userName);
        try {
            if (userService.loginByPwd(userName, passWord)) {
                if (REMEMBER_TRUE_NAME.equals(flag)) {
                    String uuid = RandomUtils.getUuid();
                    String sessionId = uuid + "";
                    Cookie cookie = new Cookie(COOKIE_LOGIN_NAME, sessionId);
                    cookie.setPath("/");
                    cookie.setMaxAge(MAX_LIVA_AGE);
                    res.addCookie(cookie);
                    String key = REDIS_LOGIN_PREFIX + COOKIE_LOGIN_NAME;
                    redisClient.set(key, userName);

                    String userlogintime = userService.getUserByUserName(userName).getUserlogintime();
                    String curdateString = BilibiliUtils.getCurdateString();
                    //  设置登录记录

                    String loginRecordKey = REDIS_RECORD_PREFIX + userName;
                    LoginRecord loginRecord = BilibiliUtils.setLoginRecord(curdateString);

                    redisClient.lpush(loginRecordKey,loginRecord.toString());
                    redisClient.expire(loginRecordKey,REDIS_MAX_AGE);

                    //  更新用户登录时间以及经验值
                    if (!userlogintime.contains(curdateString.split(" ")[0])) {
                        personalService.updateLoginTime(userName);
                        personalService.updateUserExp(userName);

                        //  登录经验奖励
                        String expKey = REDIS_EXP_PREFIX + userName;
                        ExpRecord expRecord = BilibiliUtils.setExpRecord(curdateString, LOGIN_EXP_AWARD);
                        redisClient.lpush(expKey,expRecord.toString());
                        redisClient.expire(expKey,REDIS_MAX_AGE);
                    }
                }
                result.setCode(200);
            }
        } catch (BilibiliException ex) {
            ex.printStackTrace();
            result.setCode(404);
            res.setStatus(result.getCode());
            result.setErrMsg(ex.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            result = StateUtils.is500(res);
        }
        return result;
    }

    /**
     * 手机号登录
     *
     * @param req 请求
     * @param res 响应
     * @return JSON格式
     */
    @RequestMapping(value = "users/phone", method = RequestMethod.GET)
    public JsonResult loginByPhone(HttpServletRequest req, HttpServletResponse res) {
        JsonResult result = new JsonResult();
        String userPhone = req.getParameter("userPhone");
        String code = req.getParameter("code");
        String flag = req.getParameter("flag");
        try {
            if (userService.loginByPhone(userPhone, code)) {
                if (REMEMBER_TRUE_NAME.equals(flag)) {
                    String uuid = RandomUtils.getUuid();
                    String sessionId = uuid + code;
                    Cookie cookie = new Cookie(COOKIE_LOGIN_NAME, sessionId);
                    cookie.setPath("/");
                    cookie.setMaxAge(MAX_LIVA_AGE);
                    res.addCookie(cookie);
                    String userName = userService.getUserByPhone(userPhone).getUsername();

                    redisClient.set(key, userName);


                    String userlogintime = userService.getUserByPhone(userPhone).getUserlogintime();
                    String curdateString = BilibiliUtils.getCurdateString();
                    //  设置登录记录
                    LoginRecord loginRecord = BilibiliUtils.setLoginRecord(curdateString);
                    String loginRecordKey = REDIS_RECORD_PREFIX + userName;
                    redisClient.lpush(loginRecordKey,loginRecord.toString());

                    //  更新用户登录时间以及经验值
                    if (!userlogintime.contains(curdateString.split(" ")[0])) {
                        personalService.updateLoginTime(userName);
                        personalService.updateUserExp(userName);

                        //  登录经验奖励记录
                        String expKey = REDIS_EXP_PREFIX + userName;
                        ExpRecord expRecord = BilibiliUtils.setExpRecord(curdateString, LOGIN_EXP_AWARD);
                        redisClient.lpush(expKey,expRecord.toString());
                    }
                }
                result.setCode(200);
            }
        } catch (BilibiliException ex) {
            ex.printStackTrace();
            result.setCode(404);
            res.setStatus(result.getCode());
            result.setErrMsg(ex.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            result = StateUtils.is500(res);
        }
        return result;
    }

    /**
     * 是否存在cookie信息
     *
     * @return JSON格式
     */
    @RequestMapping(value = "users/withoutCode", method = RequestMethod.GET)
    public JsonResult withoutCode(HttpServletResponse res) {
        JsonResult result = new JsonResult();
        String userName = redisClient.get(key);
        if (!StringUtils.isBlank(userName)) {
            result.setCode(200);
            result.setData(userName);
            //  更新用户登录时间以及经验值
            String userlogintime = userService.getUserByUserName(userName).getUserlogintime();
            String curdateString = BilibiliUtils.getCurdateString();
            System.out.println("上次登录："+curdateString.split(" ")[0]);
            if (!userlogintime.contains(curdateString.split(" ")[0])) {
                personalService.updateLoginTime(userName);
                personalService.updateUserExp(userName);
                //  登录经验奖励记录
                String expKey = REDIS_EXP_PREFIX + userName;
                ExpRecord expRecord = BilibiliUtils.setExpRecord(curdateString, LOGIN_EXP_AWARD);
                redisClient.lpush(expKey,expRecord.toString());
            }
        } else {
            result.setCode(200);
            result.setErrMsg("您还没有登录");
            res.setStatus(result.getCode());
        }
        return result;
    }

    /**
     * 退出功能
     *
     * @return JSON格式
     */
    //?param1=&param2=
    @RequestMapping(value = "logout", method = RequestMethod.POST)
    public JsonResult loginOut(HttpServletResponse res) {
        JsonResult result = new JsonResult();
        try {
            if (redisClient.exists(key)) {
                redisClient.del(key);
                result.setCode(200);
            } else {
                result.setCode(404);
                result.setErrMsg("您还没有登录");
                res.setStatus(result.getCode());
            }
        } catch (Exception e) {
            e.printStackTrace();
            result = StateUtils.is500(res);
        }
        return result;
    }

    /**
     * 获取用户信息
     *
     * @param req
     * @param res
     * @return
     */
    @RequestMapping(value = "users", method = RequestMethod.GET, params = "userName")
    public JsonResult getLoginUser(HttpServletRequest req, HttpServletResponse res) {
        JsonResult result = new JsonResult();
        String userName = req.getParameter("userName");
        System.out.println("logget" + userName);
        try {
            User user = userService.getUserByUserName(userName);
            if (null != user) {
                result.setCode(200);
                result.setData(user);
            } else {
                result.setCode(404);
                result.setErrMsg("用户不存在");
                res.setStatus(result.getCode());
            }
        } catch (Exception e) {
            e.printStackTrace();
            result = StateUtils.is500(res);
        }
        return result;
    }
}
